<?php

namespace App\Kuafu\ProductMenu\Model;

use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\ProductMenu\Enum\ProductMenuCodeEnum;
use App\Kuafu\ProductMenu\Exceptions\ProductMenuException;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\User\Model\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Kuafu\Base\Enum\DBEnum;
use App\Kuafu\Base\Model\BaseModel;

class ProductMenu extends BaseModel
{
    use HasFactory, KfSoftDeletes, KfUid;

    protected $connection = 'mysql';
    protected $table      = 'product_menus';
    protected $primaryKey = 'id';
    protected $fillable   = [
        'brandId',
        'name',
        'desc',
        'status',
        'createdByUid',
        'updatedByUid',
    ];

    public function createdByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'createdByUid')->select('id', 'username');
    }

    public function updatedByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'updatedByUid')->select(['id', 'username']);
    }

    public function bindShopRel()
    {
        return $this->hasMany(Shop::class, 'menuId');
    }

    /**
     * 新增
     * @return Builder|\Illuminate\Database\Eloquent\Model
     */
    public static function addData(int $brandId, string $name, string $desc)
    {
        try {
            return self::query()->create([
                'brandId' => $brandId,
                'name'    => $name,
                'desc'    => $desc,
                'status'  => DBEnum::STATUS_ON,
            ]);
        } catch (\Exception $e) {
            throw new ProductMenuException(ProductMenuCodeEnum::ERR_FOOD_MENUS_DB_ADD);
        }
    }

    /**
     * 编辑
     * @param int $id
     * @param string $name
     * @param string $desc
     * @param int $updatedByUid
     * @return int
     */
    public static function setData(int $id, string $name, string $desc, int $updatedByUid): int
    {
        return self::query()->where('id', $id)->update([
            'name'         => $name,
            'desc'         => $desc,
            'updatedByUid' => $updatedByUid
        ]);
    }

    /**
     * 上下架
     * @param int $id
     * @param int $status
     * @param string $updatedBy
     * @return int
     */
    public static function setStatus(int $id, int $status, string $updatedBy): int
    {
        return self::query()->where('id', $id)->update(['status' => $status, 'updatedBy' => $updatedBy]);
    }

    /**
     * 删除
     * @param int $id
     * @param int $updatedBy
     * @return int
     */
    public static function delData(int $id, int $updatedByUid): int
    {
        return self::query()->where('id', $id)->update(['isDeleted' => 1, 'updatedByUid' => $updatedByUid]);
    }

    /**
     * 分页列表
     * @param $productMenuId
     * @param $name
     * @param $pageSize
     * @param $pageNum
     * @param $ids
     * @param string $sortField
     * @param string $sortType
     * @return LengthAwarePaginator
     */
    public static function getDataPage($productMenuId, $name, $pageSize, $pageNum, $ids, string $sortField, string $sortType)
    {
        return self::query()
                   ->with('createdByUidRel')
                   ->with('updatedByUidRel')
                   ->withCount('bindShopRel')
                   ->where('status', DBEnum::STATUS_ON)
                   ->when(!empty($ids), function ($q) use ($ids) {
                       $q->whereIn('id', $ids);
                   })
                   ->when($name, function ($q) use ($name) {
                       $q->where('name', 'like', "%{$name}%");
                   })
                   ->when($productMenuId, function ($q) use ($productMenuId) {
                       $q->where('id', $productMenuId);
                   })
                   ->orderBy("topTime", "desc")
                    ->when($sortField, function($query)use($sortField, $sortType){
                        $query->orderBy($sortField, $sortType);
                    })
                   ->orderByDesc("id")
                   ->paginate($pageSize, ['id', 'name', 'createdAt', 'updatedAt', 'createdByUid', 'updatedByUid'],
                       $pageName = 'page', $pageNum);
    }

    /**
     * 检查重名
     * @param int $brandId
     * @param string $name
     * @param int $id
     * @return int
     */
    public static function checkName(int $brandId, string $name, int $id = 0)
    {
        return self::query()
                   ->where('brandId', $brandId)
                   ->where('name', $name)
                   ->when($id, function ($q) use ($id) {
                       $q->where('id', '!=', $id);
                   })
                   ->count();
    }

    /**
     * 检查menuId
     * @param int $brandId
     * @param int $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function checkId(int $brandId, int $id)
    {
        return self::query()->where('id', $id)->where('brandId', $brandId)->first();
    }
}
